package me.lx.tools

import android.os.Build
import timber.log.Timber
import timber.log.Timber.DebugTree

/**
 * author: luoXiong
 * date: 2019/4/19 21:34
 * version: 1.0
 * desc:
 */
class ConstTagTree : DebugTree() {
    private var mConstTag = ""
    fun setTag(tag: String): ConstTagTree {
        mConstTag = tag
        return this
    }

    private  val MAX_TAG_LENGTH = 23
    /**
     * 创建日志堆栈 TAG
     */
    override fun createStackElementTag(element: StackTraceElement): String? {
        val tag = "(" + element.fileName + ":" + element.lineNumber + ")"
        // 日志 TAG 长度限制已经在 Android 7.0 上面移除
        return if (tag.length <= MAX_TAG_LENGTH || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tag
        } else tag.substring(0, MAX_TAG_LENGTH)
    }

    override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
        //tag was originally come from Timber.tag(),so we just ignore.
        val element = callingElement()
        var newTag = mConstTag + "-" + getCallingClassName(element)
       // println("..ConstTagTree.1111...newTag=${newTag}")
       // println("..ConstTagTree.1111...message=${message}")
        //newTag= New_Ruhr-(DDOrderDetailManager.kt:79)
        // 后面的=:79: 设备=ICE  g.totalNum=0
        newTag += ":" + element.lineNumber
        super.log(priority, newTag, message, t)

    }

    fun f1(){
        val stList= arrayListOf<String>()
        for (item in stList) {

        }
    }


    private fun callingElement(): StackTraceElement {
        val stackTrace = Throwable().stackTrace
        check(stackTrace.size > CALL_STACK_INDEX) { "Synthetic stacktrace didn't have enough elements: are you using proguard?" }
        return stackTrace[CALL_STACK_INDEX]
    }

    private fun getCallingClassName(element: StackTraceElement): String? {
        return createStackElementTag(element)
    }

    companion object {
        private const val CALL_STACK_INDEX = 6
    }
}